package com.heima.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.heima.properties.AliOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

@Component
@Slf4j
public class AliOssUtil {
    @Autowired
    private AliOssProperties aliOssProperties;

    /**
     * 文件上传至阿里云OSS
     * 
     * @param bytes      文件字节数组
     * @param objectName 对象名称，例如：images/2023/10/1.jpg
     * @return 文件访问路径
     */
    public String upload(byte[] bytes, String objectName) {
        // 获取配置属性
        String endpoint = aliOssProperties.getEndpoint();
        String accessKeyId = aliOssProperties.getAccessKeyId();
        String accessKeySecret = aliOssProperties.getAccessKeySecret();
        String bucketName = aliOssProperties.getBucketName();

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,
                    new ByteArrayInputStream(bytes));

            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("文件上传成功，ETag: {}", result.getETag());

            // 返回文件访问路径
            // 访问路径格式：https://BucketName.Endpoint/ObjectName
            return "https://" + bucketName + "." + endpoint + "/" + objectName;
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
